﻿using DotNetCore.CAP;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using SHKF.B2C.BaseHosted;
using SHKF.B2C.BLL.Center;
using SHKF.B2C.Model;
using SHKF.B2C.Model.Dto;
using SHKF.B2C.Model.Entity.Center;
using SHKF.B2C.Model.Req;
using SHKF.B2C.YouZanYun.Model.Dto.Token;
using SHKF.B2C.YouZanYun.Model.Inter.CategoryPropertys;
using SHKF.B2C.YouZanYun.Model.Inter.Center;
using SHKF.B2C.YouZanYun.Model.Inter.Item;
using SHKF.B2C.YouZanYun.Model.Inter.UpdateBranch;
using SHKF.B2C.YouZanYun.Model.Inter.UpdatePrice;
using SkyApm;
using SkyApm.Tracing;
using SkyApm.Tracing.Segments;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SHKF.B2C.YouZanYun.Service.Controllers
{
    [Route("[controller]")] 
    public class NonProductController : Base2Controller
    {
        private readonly ProductInfoBLL productInfoBLL;
        private readonly ShopMapBLL shopMapBLL;

        public NonProductController(
             ProductInfoBLL productInfoBLL,
            ShopMapBLL shopMapBLL,
            IServiceProvider serviceProvider,
            ILogger<NonProductController> logger) : base(serviceProvider, logger)
        {
            this.productInfoBLL = productInfoBLL;
            this.shopMapBLL = shopMapBLL;
        }

        /// <summary>
        /// 上传产品信息到有赞云
        /// </summary>
        /// <param name="productInfo"></param>
        /// <param name="header"></param>
        /// <returns></returns>q    
        [NonAction]
        [CapSubscribe("SHKF.B2C.YZY.Product.Save", Group = "SHKF.B2C.YZY.Product")]
        public async Task<IActionResult> Save(ProductInfo productInfo, [FromCap] CapHeader header)
        {
            try
            {
                Console.WriteLine($"YZY:{productInfo.Upc}");

                base.AddLog("2.0 cap yzy save start");

                string msg = "";
                string authority_id = "";
                long app_poi_code = 0; //分店店铺SN
                long ShopSN = productInfo.ShopSN;
                long CompanySN = 0;
                if (string.IsNullOrEmpty(productInfo.Upc))
                {
                    msg = "药品UPC码不能为空";
                }

                List<ShopMapEntity> shops = this.shopMapBLL.Query(ShopSN, PlatformEnum.YouZanYun);
                if (shops == null || shops.Count == 0)
                {
                    msg += $"请在B2C平台创建虚拟商店 {ShopSN}";
                    throw new Exception(msg);
                }
                else
                {
                    CompanySN = shops[0].CompanySN;
                    app_poi_code = shops[0].app_poi_code; 
                    authority_id = this.shopMapBLL.GetKdtIdOfShopSN(ShopSN).ToString();
                }

                List<publics> publicsList = new List<publics>();
                if (msg == "")
                {
                    TokenYZYDto dtotoken = await base.GetToken(authority_id);
                    if (dtotoken.code != 200)
                    {
                        msg += dtotoken.message;
                    }
                    else
                    {
                        long leaf_category_id = 35101; //非处方:感冒解热镇痛药  
                        publicsdto dto = await publics(productInfo, authority_id, leaf_category_id);
                        if (!string.IsNullOrEmpty(dto.msg))
                        {
                            msg += dto.msg;
                        }
                        else
                        {
                            publicsList = dto.data;
                        }
                    }
                }

                if (msg != "")
                {
                    throw new Exception(msg);
                }

                string json = JsonConvert.SerializeObject(productInfo);

                base.AddLog($"2.1 => mtsg.start json:{json}");

                if (msg != "")
                {
                    throw new Exception(msg);
                }
                msg = await this.ItemAdd(authority_id, app_poi_code, productInfo, publicsList);
                if (msg != "")
                {
                    throw new Exception(msg);
                }
                base.AddLog("2.4 cap mtsg save end");
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return Ok();

        }

        private async Task<publicsdto> publics(ProductInfo product, string authority_id, long id)
        {
            publicsdto dto = new publicsdto();

            List<publics> _publics = new List<publics>();
            CategoryPropertysResult result = await this.httpClient.GetCategoryById(authority_id, id);

            if (result.success && result.data != null && result.data.public_propertys != null
            && result.data.public_propertys.Count > 0)
            {
                foreach (Public_Propertys pro in result.data.public_propertys)
                {
                    Property property = pro.property;

                    List<string> val_names = new List<string>();
                    switch (property.name)
                    {
                        case "品牌":
                            val_names.Add(product.Brand);
                            break;
                        case "产地":
                            val_names.Add(product.Made);
                            break;
                        case "生产企业":
                            val_names.Add(product.Manufacturer);
                            break;
                        case "产品剂型":
                            val_names.Add(product.Model);
                            break;
                        case "有效期":
                            val_names.Add(product.Validate.ToString());
                            break;
                        case "用法":
                            val_names.Add(product.UsageDosage);
                            break;
                        case "批准文号":
                            val_names.Add(product.LiceseId);
                            break;
                        case "采购地":
                            break;
                        case "药品分类":
                        case "国产/进口":
                        case "药品类别":
                            break;
                        case "药品通用名":
                            val_names.Add(product.CommonTitle);
                            break;
                        case "药品名称":
                            val_names.Add(product.CommonTitle);
                            break;
                        case "药品规格":
                            val_names.Add(product.Spec);
                            break;
                        case "使用剂量":
                            val_names.Add(product.UsageDosage);
                            break;
                        case "禁忌":
                            val_names.Add(product.Taboo);
                            break;
                        case "不良反应":
                            break;
                        case "贮藏条件":
                            val_names.Add(product.ConditionOfStorage);
                            break;
                        case "单位":
                            val_names.Add(product.Unit);
                            break;
                        case "包装材质":
                            break;
                        case "药品本位码":
                            break;
                        case "药品上市许可持有人":
                            break;
                        case "药品追溯码":
                            val_names.Add(product.Upc);
                            break;
                    }

                    _publics.Add(new publics() { id = property.id, val_names = val_names });
                }
            }
            else
            {
                dto.msg = result.message;
            }

            dto.data = _publics;

            return dto;
        }

        private async Task<string> ItemAdd(string authority_id, long app_poi_code, ProductInfo productInfo, List<publics> publicsList)
        {
            long leaf_category_id = 35101; //非处方:感冒解热镇痛药  
            long ShopSN = productInfo.ShopSN; 
            string msg = "";

            ParamItemRequest paramItem = new ParamItemRequest();
            Param param = new Param();
            paramItem.param = param;
            param.image_ids = new List<long>() { 4366395422, 4365490005, 4365488262 };// frmYzy.media_id; //3张图片url 
            param.title = productInfo.ProductName;
            param.quantity = 0;
            param.item_no = productInfo.ID; //产品ID
            param.barcode = productInfo.Upc;
            param.node_kdt_id = int.Parse(authority_id);//店铺SN,以前用的总店SN

            //配送
            param.item_delivery_param = new item_delivery_param();

            //类目
            category_param category_Param = new category_param();
            category_properties category_Properties = new category_properties();
            category_Properties.publics = publicsList;

            category_Properties.leaf_category_id = leaf_category_id; //新版商品类目（V4版本）叶子类目id
            category_Param.category_properties = category_Properties;
            param.category_param = category_Param;

            //价格
            param.item_price_param.price = productInfo.Price * 100;

            ItemResult result = await base.httpClient.ItemAdd(authority_id, paramItem);
            if (!result.success)
            {
                if(result.code == 221100002) //商品条码或规格条码重复,
                {

                }
                else
                {
                    msg += $"虚拟店铺{ShopSN}" + result.message;
                } 
            }
            else
            { 
                //保存总部一分
                SaveProductDB(productInfo, result.data.item_id.ToString());

                //更新分店
                string item_id = "";
                string strPoiCode = app_poi_code.ToString();
                await base.GetToken(strPoiCode);
                ItemsDto dto = await this.httpClient.ItemSearch(strPoiCode, productInfo.ID); 
                if (dto.success && dto.data.items.Count > 0)
                {
                    item_id = dto.data.items[0].item_id.ToString();
                    SaveProductMap(productInfo, authority_id, item_id);
                }
                 
                base.AddLog($"2.3 => yzy.end: Upc:{productInfo.Upc}; app_medicine_code:{productInfo.ID}");
            }

            return msg;
        }

        private void SaveProductDB(ProductInfo productInfo, string item_id)
        {
            //如果成功存总店一份Item_id,因为有赞云是以总店item_id更新分店库存和价格 
            ProductInfoEntity productInfoEntity = new ProductInfoEntity();
            productInfoEntity.CompanySN = productInfo.CompanySN;
            productInfoEntity.ShopSN = 0;
            productInfoEntity.ID = productInfo.ID;
            productInfoEntity.FKSN = productInfo.FKSN;

            this.productInfoBLL.Save(productInfoEntity);

            // 保存映射表 
            ProductInfoMapEntity productMap = new ProductInfoMapEntity();
            productMap.FKSN = productInfoEntity.SN;
            productMap.pDate = DateTime.Now;
            productMap.Platform = PlatformEnum.YouZanYun;
            productMap.app_medicine_code = item_id;
            productMap.Upc = productInfo.Upc;

            this.productInfoBLL.MapSave(productMap);
        }

        private void SaveProductMap(ProductInfo productInfo, string authority_id, string item_id)
        {
            ProductInfoMapEntity productMap = new ProductInfoMapEntity();
            productMap.FKSN = productInfo.SN;
            productMap.pDate = DateTime.Now;
            productMap.Platform = PlatformEnum.YouZanYun; 
            productMap.app_medicine_code = item_id;
            productMap.Upc = productInfo.Upc;

            this.productInfoBLL.MapSave(productMap);
        }

        /// <summary>
        /// 更新库存
        /// </summary>  
        [NonAction]
        [CapSubscribe("SHKF.B2C.YZY.Product.Stock", Group = "SHKF.B2C.YZY.Product")]
        public async Task<IActionResult> Stock(StockInfo stock, [FromCap] CapHeader header)
        {
            try
            {
                base.AddLog("2.0 cap mtsg stock start");

                string msg = "";
                List<ShopMapEntity> shops = this.shopMapBLL.Query(stock.ShopSN, PlatformEnum.YouZanYun);
                if (shops == null || shops.Count == 0)
                {
                    msg += $"请在B2C平台创建虚拟商店 {stock.ShopSN}";
                }
                if (msg != "")
                {
                    throw new Exception(msg);
                }

                //总部ID
                string authority_id = this.shopMapBLL.GetKdtIdOfShopSN(stock.ShopSN).ToString();
                this.httpClient.authority_id = authority_id;

                TokenYZYDto dtotoken = await base.GetToken(authority_id);

                if (dtotoken.code != 200)
                {
                    msg += dtotoken.message;
                }

                foreach (var item in stock.Items)
                {
                    StockUpdateRequest data = new StockUpdateRequest();
                    long root_item_id = this.productInfoBLL.GetYzyRootItemId(stock.ShopSN, item.Upc);
                    data.root_item_id = root_item_id;    //商品

                    List<ItemUpdateParam> list = new List<ItemUpdateParam>();
                    ItemUpdateParam itemUpdateParam = new ItemUpdateParam();
                    itemUpdateParam.stock_num = item.Qty;
                     
                    itemUpdateParam.node_kdt_id = shops[0].app_poi_code;  //有赞分店SN
                    list.Add(itemUpdateParam);
                    data.no_sku_update_open_param_list = list;

                    //获取有赞总部SN 
                    ItemUpdateResult result = await this.httpClient.BranchUpdateStock(data);
                    if (result.success)
                    {
                        foreach (ItemUpdateData data1 in result.data)
                        {
                            if (!data1.is_success)
                            {
                                msg += data1.message;
                            }
                        }
                    } 
                } 

                if (msg != "")
                {
                    throw new Exception(msg);
                }
                base.AddLog("2.1 cap mtsg stock end");

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                base.Release();
            }

            return Ok();
        }
       　
        /// <summary>
        /// 更新价格
        /// </summary>  
        [NonAction]
        [CapSubscribe("SHKF.B2C.YZY.Product.Price", Group = "SHKF.B2C.YZY.Product")]
        public async Task<IActionResult> Price(StockInfo stock, [FromCap] CapHeader header)
        {
            try
            {
                base.AddLog("2.0 cap mtsg stock start");

                string msg = "";
                List<ShopMapEntity> shops = this.shopMapBLL.Query(stock.ShopSN, PlatformEnum.YouZanYun);
                if (shops == null || shops.Count == 0)
                {
                    msg += $"请在B2C平台创建虚拟商店 {stock.ShopSN}";
                }
                if (msg != "")
                {
                    throw new Exception(msg);
                }

                //总部ID
                string authority_id = this.shopMapBLL.GetKdtIdOfShopSN(stock.ShopSN).ToString();
                this.httpClient.authority_id = authority_id;

                TokenYZYDto dtotoken = await base.GetToken(authority_id);

                if (dtotoken.code != 200)
                {
                    msg += dtotoken.message;
                }

                foreach (var item in stock.Items)
                {
                    PriceUpdateRequest data = new PriceUpdateRequest();
                    long root_item_id = this.productInfoBLL.GetYzyRootItemId(stock.ShopSN, item.Upc);
                    data.root_item_id = root_item_id;    //商品

                    List<PriceUpdateParam> list = new List<PriceUpdateParam>();
                    PriceUpdateParam itemUpdateParam = new PriceUpdateParam();
                    itemUpdateParam.price = (int)item.Price * 100;

                    itemUpdateParam.node_kdt_id = shops[0].app_poi_code;  //有赞分店SN
                    list.Add(itemUpdateParam);
                    data.no_sku_update_open_param_list = list;

                    //获取有赞总部SN 
                    ItemUpdateResult result = await this.httpClient.BranchUpdatePrice(data);
                    if (result.success)
                    {
                        foreach (ItemUpdateData data1 in result.data)
                        {
                            if (!data1.is_success)
                            {
                                msg += data1.message;
                            }
                        }
                    }
                }

                if (msg != "")
                {
                    throw new Exception(msg);
                }
                base.AddLog("2.1 cap mtsg stock end");

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                base.Release();
            }

            return Ok();
        }


    }

    public class publicsdto
    {
        public List<publics> data { get; set; }
        public string msg { get; set; }
    }
}
